import { defineStore } from "pinia";
import { ref, computed } from "vue";
import {useRouter} from "vue-router";
import { useUserStore } from "@/stores/userStore";
import { delFavoriteAPI, findFavoriteByIdAPI, insertFavoriteAPI, findFavoriteCountAPI} from "@/apis/favorite.js";
import {ElMessage} from "element-plus";

export const useFavoriteStore = defineStore(
    'favorite',
    () => {
        const favoriteList = ref([]);
        const userStore = useUserStore();
        const isLogin = computed(() => userStore.userInfo.token);
        const router = useRouter();

        // 获取登录后最新收藏夹列表action
        const updateLoginFavoriteList = async () => {
            const res = await findFavoriteByIdAPI(userStore.userInfo.userId)

            // 确保 favoriteList 总是一个数组
            let updatedFavoriteList = Array.isArray(res.data) ? res.data : [];

            // 更新购物车列表
            favoriteList.value = updatedFavoriteList;
        }

        const addFavorite = async (userId,productId) => {
            if (isLogin.value) {
                //登录之后加入收藏夹
                await insertFavoriteAPI(userId,productId)
                await updateLoginFavoriteList()
                ElMessage({type: 'success', message: '收藏成功'})
            } else {
                ElMessage({type: 'success', message: '请先登录'})
                router.replace({path: '/login'})
            }
        }
        // 取消收藏
        const delFavorite = async (userId,productId) => {
            if (isLogin.value) {
                //登录之后加入购物车逻辑
                await delFavoriteAPI(userId,productId)
                await updateLoginFavoriteList()
                ElMessage({type: 'success', message: '取消收藏成功'})
            } else {
                ElMessage({type: 'fail', message: '没有登录，无法删除'})
            }
        }
        // 清除收藏夹
        const clearFavorite = () => {
            favoriteList.value = []
        }
        
        return {
            favoriteList,
            addFavorite,
            delFavorite,
            updateLoginFavoriteList,
            clearFavorite,
        }
    },
    {
        persist: true
    }
)